<template>
    <div class="register_body">
        <div class="register_box">
            <!-- 第一行 -->
            <div class="register_title">
                <p>注册</p>
                <div class="toLogin">
                    已有账号, <router-link to="login">直接登录</router-link>
                </div>
            </div>
            <!-- 输入表单 -->
            <div class="register_form">
                <el-form
                    ref="ruleFormRef"
                    :model="ruleForm"
                    status-icon
                    :rules="rules"
                    label-width="auto"
                    label-position="left"
                    class="demo-ruleForm"
                >
                    <!-- 输入手机号 -->
                    <el-form-item label="手机号" prop="mobile">
                        <el-input v-model="ruleForm.mobile"   placeholder="请输入您的手机号" />
                    </el-form-item>

                    <!-- 输入验证码 -->
                    <el-form-item label="验证码" prop="code">
                        <el-input v-model="ruleForm.code"   placeholder="请输入验证码"  class="Verification"> 
                        </el-input>
                    </el-form-item>
                    <!-- 发送验证码 -->
                    <el-button type="primary"  color="#ff638a" class="getVerification" @click="sendVeriCode" v-if="butShow">获取验证码</el-button>
                    <el-button type="primary"  color="#ff638a" class="getVerification" v-if="!butShow" disabled>{{count}}</el-button>
                    <!-- 输入密码 -->
                    <el-form-item label="密码" prop="password">
                        <el-input v-model="ruleForm.password"  type="password"  placeholder="请输入您的密码"/>
                    </el-form-item>
                    <!-- 确认密码 -->
                    <el-form-item label="确认密码" prop="checkPassword">
                        <el-input v-model="checkPassword" type="password" placeholder="请再次输入您的密码"/>
                    </el-form-item>

                    <!-- 是否同意协议 -->
                    <el-checkbox v-model="checked" label="我已阅读并接受以下条款《隐私条款》、《支付用户服务协议》" size="small" />
                    <!-- 登录按钮 -->
                    <el-form-item>
                        <el-button type="primary" @click="submitForm(ruleForm)" :disabled="!checked" color="#FF8094" >注 册</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>
    </div>
</template>

<script setup>
 import { reactive, ref } from 'vue'
 import  useLoginStore  from '@/store/login'
 import { ElNotification } from 'element-plus'
 import { sendRegCode,postRegiester } from '@/api'
 import { getRandom } from '@/utils/random'
 import { useRouter } from 'vue-router'
    const router = useRouter()
    const LoginStore = useLoginStore()
    //获取到表单组件
    let ruleFormRef = ref()
    let ruleForm = reactive({
        code:null,
        mobile: null,
        password: null,
        username:null,
    })
    let checkPassword = ref(null)
    let result = ref(null)
    // 定义是否禁用按钮
    // 双向数据绑定是否选中同意协议
    let checked = ref(false)
    //定义show判断发送验证码按钮是否倒计时
    let butShow = ref(true)
    //定义倒计时
    let count = ref(60)
    //用于存计时器返回值
    let timer = null

    // 点击发送验证码
    const sendVeriCode = async() => {
        //如何输入了手机号则发送验证码请求并做倒计时
        result = await sendRegCode({
          mobile:ruleForm.mobile,
        })
        console.log(result)
        if(result.code == 200){
            // 模拟手机接收到短信
            setTimeout(()=>{
                ElNotification({
                type: 'info',
                message: `您的验证码是${result.user.code}`,
                duration: 5000,
              })
            },4000)
            //调整按钮样式，倒计时
            const TIME_COUNT = 60;
            if(!timer){
              count.value = TIME_COUNT;
              butShow.value = false;
              timer = setInterval(()=>{
                if(count.value>0 && count.value <= TIME_COUNT){
                  count.value -- ;
                }else{
                  butShow.value = true;
                  clearInterval(timer);
                  timer = null
                }
              },1000)
            }
        }
    }

    // 定义注册按钮
    const submitForm = async(ruleForm) =>{
        if(ruleForm.code !== result.user.code){
            ElNotification({
                type: 'error',
                message: `验证码错误`,
                duration: 5000,
            })
        }else if(ruleForm.mobile !== result.user.mobile){
            ElNotification({
                type: 'error',
                message: `手机号错误`,
                duration: 5000,
            })
        }else if(checkPassword !== ruleForm.password){
            ElNotification({
                type: 'error',
                message: `两次密码不对`,
                duration: 5000,
            })
        }else{
            //发送注册请求
            ruleForm.username = `美呀用户${getRandom(10000,99999)}`
            const res = await postRegiester(ruleForm);
            console.log(res)
            if(res.code == 200){
                ElNotification({
                type: 'success',
                message: `注册成功`,
                duration: 5000,
               })
                setTimeout(()=>{
                    router.replace('/login')
                },1000)
            }else{
                ElNotification({
                type: 'error',
                message: `${res.msg}`,
                duration: 5000,
               })
            }
        }
    }
    //定义校验函数
    // 校验手机号
    const validatePhone = (rule, value, callback) => {
        if (!value) {
            callback(new Error('手机号不能为空'))
        } else if(!LoginStore.reg_phone.test(value)) {
            callback(new Error('请输入正确的手机号'))
        }else {
            callback()
        }
    }
    // 校验验证码
    const validateVerification = (rule, value, callback) => {
        console.log(value)
        if (!value) {
            callback(new Error('验证码不能为空'))
        } else if(!LoginStore.reg_veriCode.test(value)) {
            callback(new Error('请输入四位数字'))
        }else{
            callback()
        }
    }
    // 验证密码
    const validatePass = (rule, value, callback) => {
        if (!value) {
            callback(new Error('密码不能为空'))
        }else if(!LoginStore.reg_password.test(value)){
            callback(new Error('请重新输入6~16位数字加字母的密码'))
        }else {
            if (checkPassword.value !== '') {
                if (!ruleFormRef.value) return
                ruleFormRef.value.validateField('checkPassword', () => null)
            }
            callback()
        }
    }
    // 验证两次密码是否输入正确
    const validateCheckPass = (rule, value, callback) => {
        if (checkPassword.value === '') {
            callback(new Error('请再次输入密码'))
        } else if (checkPassword.value !== ruleForm.password) {
            callback(new Error("两次密码不一样"))
            // checked = false;
        } else {
            callback()
            // checked = true;
        }
    }
    //定义校验规则
    const rules = reactive({
        mobile: [{ validator: validatePhone, trigger: 'blur' }],
        code: [{ validator: validateVerification, trigger: 'blur' }],
        password: [{ validator: validatePass, trigger: 'blur' }],
        checkPassword: [{ validator: validateCheckPass, trigger: 'blur' }],
    })
</script>

<style scoped>
.register_body{
    width: 100%;
    height: 600px;
    background-image: url('@/assets/img/background4.png');
    background-size: 980px 600px;
    background-repeat:no-repeat;
    background-position: center;
    background-color: #fbf7f8;
}
.register_box{
    width: 460px;
    height: 478px;
    background-color:#fefefe;
    float: right;
    margin-right: 250px;
    margin-top: 50px;
    opacity:0.9;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    position: relative;
}
.register_title{
    width: 400px;
    height: 60px;
    line-height: 60px;
}
.register_title>p{
    font-size: 22px;
    font-weight: 500;
    float: left;
}
.toLogin{
    float: right;
    font-size: 14px;
}
.register_title a{
    color: #ff8aa5;
}
.register_form{
    width: 400px;
}
/* 输入框样式 */
:deep(.el-input__wrapper){
    height: 50px;
}
:deep(.el-form-item__label){
    height: 50px;
    line-height: 50px;
    font-size: 14px;
    color: #333;
}
/* 按钮样式 */
:deep(.el-button){
    width: 400px;
    height: 60px;
    color: #fff;
    font-size: 22px;
    margin-top: 10px;
}

.Verification {
    width: 135px;
}
.getVerification{
 width: 170px;
 height: 52px; 
 font-size: 16px;
 position: absolute;
 top: 132px;
 right: 32px;
}
</style>